import { ref } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import {useGetPersonalInfo} from "@/api/getPersonalInfo";
import {useGetUserInfoInCard} from "@/api/getUserInfoInCard";
import {useGetTaskRecordByReceiver} from "@/api/getTaskRecordsByReceiver";
import {useGetTaskRecordBySender} from "@/api/getTaskRecordsBySender";

/**
 * 密码登录请求
 * @returns { handlePasswordLogin, phoneNumber, password, isLoading }
 */
export function passwordLogin() {
    const phoneNumberPassword = ref(""); // 手机号
    const password = ref(""); // 密码
    const isLoading = ref(false); // 加载状态

    const store = useStore(); // 获取 Vuex Store 实例
    const router = useRouter(); // 获取 Vue Router 实例
    // 获取 handleGetPersonalInfo 方法
    const { handleGetPersonalInfo } = useGetPersonalInfo();
    const { handleGetUserInfoInCard } = useGetUserInfoInCard();
    const { handleGetTaskRecordByReceiver } = useGetTaskRecordByReceiver();
    const { handleGetTaskRecordBySender } = useGetTaskRecordBySender();
    // 处理密码登录
    const handlePasswordLogin = async () => {
        // 简单的表单验证
        if (!phoneNumberPassword.value || !password.value) {
            alert("请输入手机号和密码");
            return;
        }

        isLoading.value = true; // 设置加载状态为 true

        try {
            // 调用 Vuex 中的 login action
            const response = await store.dispatch("login", {
                phoneNumber: phoneNumberPassword.value,
                password: password.value,
            });
            if (response.success) {
                alert("登录成功");
                // 获取用户个人信息
                await handleGetPersonalInfo();
                await handleGetUserInfoInCard();
                await handleGetTaskRecordByReceiver();
                await handleGetTaskRecordBySender();
                await router.push("/home"); // 跳转到首页
            } else {
                alert(response.message || "登录失败");
            }
        } catch (error) {
            console.error("登录错误:", error);
            alert("登录失败，请检查网络或稍后再试");
        } finally {
            isLoading.value = false; // 重置加载状态
        }
    };

    // 返回封装的响应式变量和方法
    return {
        handlePasswordLogin,
        phoneNumberPassword,
        password,
        isLoading,
    };
}
